using NetworkFlowMonitor.Scripts.Data;
using NetworkFlowMonitor.Scripts.Service;

namespace NetworkFlowMonitor.Scripts.Controllers;

// Controllers/Api/TrafficController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

[ApiController]
[Route("api/[controller]")]
public class TrafficController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public TrafficController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet("devices")]
    public async Task<ActionResult<IEnumerable<Device>>> GetDevices()
    {
        return await _context.Devices
            .OrderBy(d => d.DeviceName)
            .ToListAsync();
    }

    [HttpGet("latest")]
    public async Task<ActionResult<IEnumerable<TrafficUpdate>>> GetLatestTraffic()
    {
        // 检查TrafficMonitorService是否已初始化
        if (TrafficMonitorService.Instance == null)
        {
            return Ok(new List<TrafficUpdate>());
        }
        
        var updates = TrafficMonitorService.Instance.GetLatestTraffic();
        return Ok(updates);
    }

    [HttpGet("history/{deviceId}")]
    public async Task<ActionResult<IEnumerable<TrafficRecord>>> GetTrafficHistory(int deviceId,
        DateTime? startDate = null, DateTime? endDate = null)
    {
        var query = _context.TrafficRecords
            .Where(r => r.DeviceId == deviceId)
            .OrderBy(r => r.Timestamp);

        if (startDate.HasValue)
            query = query.Where(r => r.Timestamp >= startDate.Value).OrderBy(r => r.Timestamp);

        if (endDate.HasValue)
            query = query.Where(r => r.Timestamp <= endDate.Value).OrderBy(r => r.Timestamp);
        else
            query = query.Take(100).OrderBy(r => r.Timestamp); // 默认取最近100条

        return Ok(await query.ToListAsync());
    }

    [HttpGet("summary")]
    public async Task<ActionResult> GetSummary()
    {
        var totalDevices = await _context.Devices.CountAsync();
        // 使用可以翻译为SQL的表达式来判断设备是否活跃
        var activeDevices = await _context.Devices.CountAsync(d => d.LastSeen >= DateTime.UtcNow.AddMinutes(-1));

        // 直接使用eth1接口的统计数据
        var totalDownload = 0L;
        var totalUpload = 0L;
        
        // 检查TrafficMonitorService是否已初始化
        if (TrafficMonitorService.Instance != null)
        {
            var latestUpdates = TrafficMonitorService.Instance.GetLatestTraffic();
            totalDownload = latestUpdates.Sum(t => t.TotalDownload);
            totalUpload = latestUpdates.Sum(t => t.TotalUpload);
        }

        return Ok(new
        {
            TotalDevices = totalDevices,
            ActiveDevices = activeDevices,
            TotalDownload = totalDownload,
            TotalUpload = totalUpload,
            LastUpdated = DateTime.UtcNow
        });
    }
}